package site.xuxingcan.NettyUtil;

import com.google.gson.Gson;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import site.xuxingcan.NettyUtil.Handler.LoginHandler;
import site.xuxingcan.NettyUtil.Handler.RoomActionHandler;

/**
 * Created by xuxingcan on 16-7-24.
 */
public class NettyUtil {
    public static Gson gson = new Gson();

    public static void main(String[] arg) throws InterruptedException {
        new NettyUtil().start();
    }

    public void start() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(8090)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //编码
                            socketChannel.pipeline().addLast(new JsonEncoder());
                            //解码
                            socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024 * 1024));
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new JsonDecoder());
                            //逻辑处理
                            socketChannel.pipeline().addLast(new LoginHandler());
                            socketChannel.pipeline().addLast(new RoomActionHandler());
                        }
                    });
            ChannelFuture f = bootstrap.bind().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}